import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  Switch, 
  message, 
  Popconfirm,
  Divider,
  Row,
  Col
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  KeyOutlined,
  SearchOutlined,
  ReloadOutlined,
  UserOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Search } = Input;
const { Option } = Select;

// 用户数据接口
interface UserData {
  id: string;
  loginName: string;
  userName: string;
  phone: string;
  email?: string;
  roles: RoleData[];
  status: boolean;
  createTime: string;
  updateTime: string;
  updateByUserName: string;
}

// 角色数据接口
interface RoleData {
  id: string;
  roleName: string;
  roleCode: string;
}

// 模拟角色数据
const mockRoles: RoleData[] = [
  { id: '1', roleName: '系统管理员', roleCode: 'ADMIN' },
  { id: '2', roleName: '运维人员', roleCode: 'OPERATOR' },
  { id: '3', roleName: '普通用户', roleCode: 'USER' },
  { id: '4', roleName: '访客', roleCode: 'GUEST' }
];

// 模拟用户数据
const mockUserData: UserData[] = [
  {
    id: '1',
    loginName: 'admin',
    userName: '系统管理员',
    phone: '13800138000',
    email: 'admin@example.com',
    roles: [mockRoles[0]],
    status: true,
    createTime: '2024-01-15 10:30:00',
    updateTime: '2024-01-20 14:30:25',
    updateByUserName: '系统管理员'
  },
  {
    id: '2',
    loginName: 'operator01',
    userName: '张三',
    phone: '13800138001',
    email: 'zhangsan@example.com',
    roles: [mockRoles[1]],
    status: true,
    createTime: '2024-01-16 09:15:00',
    updateTime: '2024-01-19 16:20:10',
    updateByUserName: '系统管理员'
  },
  {
    id: '3',
    loginName: 'user01',
    userName: '李四',
    phone: '13800138002',
    email: 'lisi@example.com',
    roles: [mockRoles[2]],
    status: false,
    createTime: '2024-01-17 14:45:00',
    updateTime: '2024-01-18 11:30:45',
    updateByUserName: '张三'
  },
  {
    id: '4',
    loginName: 'guest01',
    userName: '王五',
    phone: '13800138003',
    roles: [mockRoles[3]],
    status: true,
    createTime: '2024-01-18 16:20:00',
    updateTime: '2024-01-20 09:15:30',
    updateByUserName: '张三'
  }
];

const UserList: React.FC = () => {
  const [userData, setUserData] = useState<UserData[]>(mockUserData);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState<boolean | undefined>(undefined);
  
  // 模态框状态
  const [isAddModalVisible, setIsAddModalVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [isResetPasswordModalVisible, setIsResetPasswordModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<UserData | null>(null);
  
  // 表单实例
  const [addForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [resetPasswordForm] = Form.useForm();

  // 过滤数据
  const filteredData = userData.filter(user => {
    const matchesSearch = !searchText || 
      user.userName.toLowerCase().includes(searchText.toLowerCase()) ||
      user.loginName.toLowerCase().includes(searchText.toLowerCase()) ||
      user.phone.includes(searchText);
    
    const matchesStatus = statusFilter === undefined || user.status === statusFilter;
    
    return matchesSearch && matchesStatus;
  });

  // 表格列配置
  const columns: ColumnsType<UserData> = [
    {
      title: '序号',
      key: 'index',
      width: 80,
      render: (_, __, index) => index + 1,
    },
    {
      title: '账号名称',
      dataIndex: 'loginName',
      key: 'loginName',
      width: 150,
    },
    {
      title: '用户名称',
      dataIndex: 'userName',
      key: 'userName',
      width: 150,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 130,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 180,
      render: (email) => email || '--',
    },
    {
      title: '授权角色',
      dataIndex: 'roles',
      key: 'roles',
      width: 150,
      render: (roles: RoleData[]) => (
        <div>
          {roles.map(role => (
            <Tag key={role.id} color="blue">{role.roleName}</Tag>
          ))}
        </div>
      ),
    },
    {
      title: '账号状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: boolean) => (
        <Tag color={status ? 'green' : 'red'}>
          {status ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 160,
    },
    {
      title: '编辑人员',
      dataIndex: 'updateByUserName',
      key: 'updateByUserName',
      width: 120,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            icon={<KeyOutlined />} 
            size="small"
            onClick={() => handleResetPassword(record)}
          >
            重置密码
          </Button>
          <Popconfirm
            title="确定删除该用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="link" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  // 处理刷新
  const handleRefresh = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      message.success('数据刷新成功');
    }, 1000);
  };

  // 处理添加用户
  const handleAdd = () => {
    setIsAddModalVisible(true);
  };

  // 处理编辑用户
  const handleEdit = (user: UserData) => {
    setEditingUser(user);
    editForm.setFieldsValue({
      ...user,
      roleIds: user.roles.map(role => role.id)
    });
    setIsEditModalVisible(true);
  };

  // 处理重置密码
  const handleResetPassword = (user: UserData) => {
    setEditingUser(user);
    resetPasswordForm.setFieldsValue({
      loginName: user.loginName,
      userName: user.userName
    });
    setIsResetPasswordModalVisible(true);
  };

  // 处理删除用户
  const handleDelete = (userId: string) => {
    setUserData(prev => prev.filter(user => user.id !== userId));
    message.success('用户删除成功');
  };

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的用户');
      return;
    }
    
    Modal.confirm({
      title: '确定删除选中的用户吗？',
      content: `将删除 ${selectedRowKeys.length} 个用户`,
      onOk: () => {
        setUserData(prev => prev.filter(user => !selectedRowKeys.includes(user.id)));
        setSelectedRowKeys([]);
        message.success('批量删除成功');
      }
    });
  };

  // 提交添加用户表单
  const handleAddSubmit = (values: any) => {
    const newUser: UserData = {
      id: Date.now().toString(),
      loginName: values.loginName,
      userName: values.userName,
      phone: values.phone,
      email: values.email,
      roles: mockRoles.filter(role => values.roleIds.includes(role.id)),
      status: values.status,
      createTime: new Date().toLocaleString(),
      updateTime: new Date().toLocaleString(),
      updateByUserName: '当前用户'
    };
    
    setUserData(prev => [...prev, newUser]);
    setIsAddModalVisible(false);
    addForm.resetFields();
    message.success('用户添加成功');
  };

  // 提交编辑用户表单
  const handleEditSubmit = (values: any) => {
    if (!editingUser) return;
    
    const updatedUser: UserData = {
      ...editingUser,
      userName: values.userName,
      phone: values.phone,
      email: values.email,
      roles: mockRoles.filter(role => values.roleIds.includes(role.id)),
      status: values.status,
      updateTime: new Date().toLocaleString(),
      updateByUserName: '当前用户'
    };
    
    setUserData(prev => prev.map(user => 
      user.id === editingUser.id ? updatedUser : user
    ));
    setIsEditModalVisible(false);
    setEditingUser(null);
    editForm.resetFields();
    message.success('用户更新成功');
  };

  // 提交重置密码表单
  const handleResetPasswordSubmit = (values: any) => {
    // 这里应该调用重置密码的API
    console.log('重置密码:', values);
    setIsResetPasswordModalVisible(false);
    setEditingUser(null);
    resetPasswordForm.resetFields();
    message.success('密码重置成功');
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
          <Col span={8}>
            <Search
              placeholder="搜索用户名、账号或手机号"
              allowClear
              onSearch={handleSearch}
              style={{ width: '100%' }}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="账号状态"
              allowClear
              style={{ width: '100%' }}
              onChange={setStatusFilter}
            >
              <Option value={true}>启用</Option>
              <Option value={false}>禁用</Option>
            </Select>
          </Col>
          <Col span={12} style={{ textAlign: 'right' }}>
            <Space>
              <Button 
                icon={<ReloadOutlined />} 
                onClick={handleRefresh}
              >
                刷新
              </Button>
              <Button 
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleBatchDelete}
              >
                批量删除
              </Button>
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={handleAdd}
              >
                新增用户
              </Button>
            </Space>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={filteredData}
          rowKey="id"
          loading={loading}
          rowSelection={rowSelection}
          scroll={{ x: 1200 }}
          pagination={{
            total: filteredData.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      {/* 添加用户模态框 */}
      <Modal
        title="新增用户"
        open={isAddModalVisible}
        onCancel={() => {
          setIsAddModalVisible(false);
          addForm.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={addForm}
          layout="vertical"
          onFinish={handleAddSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="loginName"
                label="账号名称"
                rules={[{ required: true, message: '请输入账号名称' }]}
              >
                <Input placeholder="请输入账号名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="userName"
                label="用户名称"
                rules={[{ required: true, message: '请输入用户名称' }]}
              >
                <Input placeholder="请输入用户名称" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="手机号"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                ]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { type: 'email', message: '请输入正确的邮箱格式' }
                ]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="roleIds"
            label="授权角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select
              mode="multiple"
              placeholder="请选择角色"
              style={{ width: '100%' }}
            >
              {mockRoles.map(role => (
                <Option key={role.id} value={role.id}>
                  {role.roleName}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="status"
            label="账号状态"
            valuePropName="checked"
            initialValue={true}
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => {
                setIsAddModalVisible(false);
                addForm.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑用户模态框 */}
      <Modal
        title="编辑用户"
        open={isEditModalVisible}
        onCancel={() => {
          setIsEditModalVisible(false);
          setEditingUser(null);
          editForm.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={editForm}
          layout="vertical"
          onFinish={handleEditSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="loginName"
                label="账号名称"
              >
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="userName"
                label="用户名称"
                rules={[{ required: true, message: '请输入用户名称' }]}
              >
                <Input placeholder="请输入用户名称" />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="手机号"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                ]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { type: 'email', message: '请输入正确的邮箱格式' }
                ]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="roleIds"
            label="授权角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select
              mode="multiple"
              placeholder="请选择角色"
              style={{ width: '100%' }}
            >
              {mockRoles.map(role => (
                <Option key={role.id} value={role.id}>
                  {role.roleName}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="status"
            label="账号状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => {
                setIsEditModalVisible(false);
                setEditingUser(null);
                editForm.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 重置密码模态框 */}
      <Modal
        title="重置密码"
        open={isResetPasswordModalVisible}
        onCancel={() => {
          setIsResetPasswordModalVisible(false);
          setEditingUser(null);
          resetPasswordForm.resetFields();
        }}
        footer={null}
        width={400}
      >
        <Form
          form={resetPasswordForm}
          layout="vertical"
          onFinish={handleResetPasswordSubmit}
        >
          <Form.Item
            name="loginName"
            label="账号名称"
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            name="userName"
            label="用户名称"
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度至少6位' }
            ]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>
          <Form.Item
            name="confirmPassword"
            label="确认密码"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请确认密码" />
          </Form.Item>
          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => {
                setIsResetPasswordModalVisible(false);
                setEditingUser(null);
                resetPasswordForm.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserList;